<template>
  <!-- 模板保持不变 -->
  <el-select
      v-model="selectedJobNum"
      filterable
      clearable
      remote
      :disabled="disabled"
      reserve-keyword
      placeholder="请选择工作号"
      :remote-method="remoteSearch"
      :loading="loading"
      @change="handleChange"
  >
    <el-option
        v-for="item in displayedOptions"
        :key="item.JobNum"
        :label="item.JobNum"
        :value="item.JobNum"
    >
      <span style="float: left">{{ item.ProjectName }}</span>
      <span style="float: right; color: var(--el-text-color-secondary); font-size: 13px">
        【{{ item.JobNum }}】
      </span>
    </el-option>
  </el-select>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElSelect, ElOption } from 'element-plus'
import { cubasdocStore } from '@/stores/modules/cubasdoc'

const cubasdoc = cubasdocStore()

const emit = defineEmits(['update:modelValue', 'change'])

const props = defineProps({
  contractList: {
    type: Array,
    default: () => []
  },
  disabled: {
    type: Boolean,
    default: false
  },
  isUseGlobalData: {
    type: Boolean,
    default: true
  }
})

const selectedJobNum = ref('')
const loading = ref(false)
const keyword = ref('')

// 统一获取数据源的方法
const getDataSource = () => {
  if (props.contractList?.length > 0) return props.contractList
  if (props.isUseGlobalData) return cubasdoc.contractList
  return []
}

// 修复后的搜索逻辑
const displayedOptions = computed(() => {
  const source = getDataSource()
  const kw = keyword.value ? keyword.value.trim().toLowerCase() : ''

  if (!kw) return source

  return source.filter(item => {
    if (!item.JobNum) return false

    // 统一转换为字符串并小写
    const jobNum = String(item.JobNum).toLowerCase()
    const projectName = item.ProjectName ? String(item.ProjectName).toLowerCase() : ''

    return jobNum.includes(kw) || projectName.includes(kw)
  })
})

const remoteSearch = (query) => {
  keyword.value = query
  loading.value = true
  setTimeout(() => {
    loading.value = false
  }, 200)
}

// 修复后的change处理
const handleChange = (value) => {
  emit('update:modelValue', value)

  // 使用与displayedOptions相同的数据源
  const source = getDataSource()
  const selectedItem = source.find(item =>
      item.JobNum && String(item.JobNum) === String(value)
  )

  emit('change', selectedItem || null)
}
</script>
